package com.naiterui.ehp.bs.weixin.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.weixin.config.WxMaConfiguration;
import com.naiterui.ehp.bs.weixin.exception.WeixinCode;
import com.naiterui.ehp.bs.weixin.exception.WeixinException;
import com.naiterui.ehp.bs.weixin.properties.WeixinProperties;
import com.naiterui.ehp.bs.weixin.service.QrCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

/**
 * 微信二维码
 *
 * @author guoyongxiang
 * @version 1.0.0
 * @date 2022/10/24 10:15
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class QrCodeServiceImpl implements QrCodeService {

    private final WeixinProperties weixinproperties;

    @Override
    public String getMaUnlimitedQRCodeUrl(String scene, String page) throws WeixinException, IOException {
        String appid = weixinproperties.getAppId();
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        // 生成小程序码
        File file;
        try {
            file = wxService.getQrcodeService().createWxaCodeUnlimit(scene, page);
        } catch (WxErrorException e) {
            log.warn("小程序二维码生成失败 scene:{}", scene, e);
            throw new WeixinException(WeixinCode.WECHAT_QRCODE_GENERATE_FAILE);
        }
        // 下载小程序码生成图片链接
        String imagePath = ConfigUtil.getString("ehp.miniapp-qrcode") + scene + ".png";
        String filePath = ConfigUtil.getString("file.base.prefix") + imagePath;
        FileUtils.copyFile(file, new File(filePath));

        return ConfigUtil.getString("ehp.domain.img") + imagePath;
    }
}
